import express from 'express';
import { createServer } from 'http';
import { WebSocketServer } from 'ws';
import cors from 'cors';
import { ServiceManager } from './services/ServiceManager';
import { setupRoutes } from './routes';

const app = express();
const server = createServer(app);
const wss = new WebSocketServer({ server });

// 中间件
app.use(cors());
app.use(express.json());

// 创建服务管理器实例
const serviceManager = new ServiceManager(wss);

// 设置路由
setupRoutes(app, serviceManager);

// WebSocket连接处理
wss.on('connection', (ws) => {
  console.log('客户端连接到WebSocket');
  
  ws.on('close', () => {
    console.log('客户端断开WebSocket连接');
  });
});

const PORT = process.env.PORT || 8080;
// IIS环境下使用命名管道
// 开发环境使用TCP端口
const listener = process.env.IISNODE_VERSION 
  ? process.env.PORT 
  : PORT;

server.listen(listener, () => {
  console.log(`服务管理器服务已启动`);
  if (process.env.IISNODE_VERSION) {
    console.log('IIS环境：使用命名管道');
  } else {
    console.log(`端口: ${PORT}`);
  }
});